package epsi.mobile.views;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import epsi.mobile.adapters.MapInfoAdapter;
import epsi.mobile.business.StoreProcess;
import epsi.mobile.constants.ConfigurationConstants;
import epsi.mobile.constants.LocalisationConstants;
import epsi.mobile.entities.Store;
import epsi.mobile.helpers.GPSTracker;
import epsi.mobile.helpers.ProximitySearchHelper;
import epsi.mobile.storelocator.R;

public class StoreMapActivity extends Activity {

    private GoogleMap map;
    private GPSTracker gps;
    
    private Bundle getRequest;
    private String request;
    
    private double currentLatitude;
    private double currentLongitude;

    private ArrayList<Store> storesToShow;
    private HashMap<Marker,String> mapMarkers;
    
    private StoreProcess storeProcess;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.storemap);
      
      initMap(); // Init the map
    }

	private void initMap() 
	{
		storesToShow = new ArrayList<Store>();
		mapMarkers = new HashMap<Marker,String>();
		storeProcess = new StoreProcess(getApplicationContext());
		
		getRequest = getIntent().getExtras(); //Get the request
		request = getRequest.getString("mapRequest");
		
		if(request.equals(ConfigurationConstants.MapProximityRequest)) // If it's a proximity Research
		{
			gps = new GPSTracker();
			
	        	currentLatitude = GPSTracker.latitude;
	        	currentLongitude = GPSTracker.longitude;
            	
            	storesToShow = storeProcess.getNearbyStores(currentLatitude,currentLongitude);
            	
            	CreateMap(storesToShow);
		}
		else // If it's a user research
		{		
		    if(!request.equals(""))
		    {
		        ProximitySearchHelper prox = new ProximitySearchHelper(this);
		        prox.execute(request);
		        try
                {
		            LatLng lat = prox.get();
		            
		            if(lat != null)
		            	storesToShow = storeProcess.getNearbyStores(lat.latitude, lat.longitude);	
		            
		            CreateMap(storesToShow);
                }
                catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (ExecutionException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
		    }
		    else // If no value entered by the user, return all stores
		    {
		    	this.storesToShow = this.storeProcess.getAllStores();
		    	 CreateMap(storesToShow);
		    }	
		}		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.map, menu);
		return true;
	}
	
    public boolean onOptionsItemSelected(MenuItem item) 
    {
		switch (item.getItemId()) {
		case R.id.action_list:
			Intent listIntent = new Intent(StoreMapActivity.this, StoreListActivity.class);
			listIntent.putExtra("listRequest",request);
	    	startActivity(listIntent);
	    	StoreMapActivity.this.finish();
		  break;	
		}
		return true;
	}
	
	private void CreateMap(ArrayList<Store> storesToShow)
	{
		LatLng first = null;
		
		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // Create the map
		map.setMyLocationEnabled(true);
		map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker marker) {
				Intent detailsIntent = new Intent(StoreMapActivity.this, StoreDetailsActivity.class);
	        	detailsIntent.putExtra("storeId",mapMarkers.get(marker));
	        	startActivity(detailsIntent);
				
			}
		});
		map.setInfoWindowAdapter(new MapInfoAdapter(this));
		
		for(int i=0;i<storesToShow.size();i++)
		{	
			if(i==0)
				first = new LatLng(storesToShow.get(i).getXposition(),storesToShow.get(i).getYposition());
			
			Marker m = map.addMarker(new MarkerOptions()
		      .position(new LatLng(storesToShow.get(i).getXposition(),storesToShow.get(i).getYposition()))
		      .title(storesToShow.get(i).getStoreName())
		      .snippet(storesToShow.get(i).getAdress()+"\n"+storesToShow.get(i).getPostalCode() + " " + storesToShow.get(i).getCity()));
			mapMarkers.put(m,storesToShow.get(i).getStoreId());		
			
			
		}		
		
		if(first != null)
		{
			map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(first.latitude,first.longitude), 5)); // Position per default : first store in the list
			map.animateCamera(CameraUpdateFactory.zoomTo(8), 2000, null); // Zoom animation	
		}
	}
}
